package com.ruoyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.Article;
import com.ruoyi.domain.Conlumn;
import com.ruoyi.domain.RecoverStation;
import com.ruoyi.domain.vo.ArticleColumnVo;
import com.ruoyi.domain.vo.ArticleOriginDateVo;
import com.ruoyi.domain.vo.DeptArticleCountVo;
import com.ruoyi.mapper.ArticleMapper;
import com.ruoyi.mapper.ConlumnMapper;
import com.ruoyi.mapper.RecoverStationMapper;
import com.ruoyi.service.ArticleService;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * articleService业务层处理
 *
 * @author ruoyi
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private PdfParseTaskServiceImpl pdfParseTaskService;

    @Autowired
    private ConlumnMapper conlumnMapper;

    @Autowired
    private RecoverStationMapper recoverStationMapper;


    /**
     * 判断部门是否直接隶属于荆州市长江河道管理局（一级子部门）
     * @param dept 部门信息
     * @return 是否直接隶属于荆州市长江河道管理局
     */
    private boolean isDirectSubDeptOfJingZhou(SysDept dept) {
        // 如果部门本身就是"荆州市长江河道管理局"，则不认为是其下级部门
        if ("荆州市长江河道管理局".equals(dept.getDeptName())) {
            return false;
        }
        
        // 直接检查父部门是否为"荆州市长江河道管理局"
        // 如果父部门ID有效，直接查询父部门名称
        if (dept.getParentId() != null && dept.getParentId() > 0) {
            SysDept parentDept = sysDeptMapper.selectDeptById(dept.getParentId());
            if (parentDept != null && "荆州市长江河道管理局".equals(parentDept.getDeptName())) {
                return true;
            }
        }
        
        return false;
    }
    @Override
    public List<ArticleColumnVo> selectAllDeptArticleColumnList(String startTime, String endTime) {
        // 如果没有指定时间范围，默认查询本年1月1日到当前日期
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            String yearStart = DateUtils.dateTimeNow("yyyy") + "-01-01";
            String today = DateUtils.dateTimeNow("yyyy-MM-dd");
            startTime = yearStart;
            endTime = today;
        }

        System.out.println("输入参数: startTime=" + startTime + ", endTime=" + endTime);

        // 查询所有文章，不按部门过滤
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Article::getColumnId, Article::getArticleOrigin); // 只选择需要的字段
        wrapper.ge(Article::getPubdate, startTime);
        wrapper.le(Article::getPubdate, endTime);
        wrapper.isNotNull(Article::getArticleOrigin);
        wrapper.ne(Article::getArticleOrigin, "");

        System.out.println("查询条件: " + wrapper.getSqlSegment());
        List<Article> articles = articleMapper.selectList(wrapper);
        System.out.println("查询结果数量: " + articles.size());

        if (articles.isEmpty()) {
            System.out.println("未查询到数据，返回空列表");
            return new ArrayList<>();
        }

        // 获取所有栏目信息
        List<Conlumn> allColumns = conlumnMapper.selectList(null);
        Map<Long, Conlumn> columnMap = new HashMap<>();
        for (Conlumn column : allColumns) {
            columnMap.put(column.getId(), column);
        }

        // 初始化所有栏目计数为0
        Map<String, Integer> columnCountMap = new HashMap<>();
        for (Conlumn column : allColumns) {
            columnCountMap.put(column.getName(), 0);
        }

        // 统计各栏目文章数量（不限制栏目权限）
        int nullColumnCount = 0; // 用于统计栏目为null的文章数量
        for (Article article : articles) {
            Long columnId = article.getColumnId();
            if (columnId != null) {
                Conlumn column = columnMap.get(columnId);
                if (column != null) {
                    String columnName = column.getName();
                    columnCountMap.put(columnName, columnCountMap.getOrDefault(columnName, 0) + 1);
                }
            } else {
                // 栏目为null的文章数量统计
                nullColumnCount++;
            }
            System.out.println("未知栏目数量："+nullColumnCount);
        }

        // 如果有栏目为null的文章，添加到结果中
        if (nullColumnCount > 0) {
            columnCountMap.put("未知栏目", nullColumnCount);
        }

        // 转换为返回格式
        List<ArticleColumnVo> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : columnCountMap.entrySet()) {
            ArticleColumnVo vo = new ArticleColumnVo();
            vo.setColumnName(entry.getKey());
            vo.setCount(entry.getValue());
            result.add(vo);
        }

        // 按文章数量排序
        result.sort((a, b) -> b.getCount());

        System.out.println("最终结果: " + result);

        return result;
    }

    @Override
    public List<ArticleColumnVo> selectArticleColumnListByDept(String deptName, String startTime, String endTime) {
        // 如果没有指定时间范围，默认查询本年1月1日到当前日期
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            String yearStart = DateUtils.dateTimeNow("yyyy") + "-01-01";
            String today = DateUtils.dateTimeNow("yyyy-MM-dd");
            startTime = yearStart;
            endTime = today;
        }

        System.out.println("输入参数: deptName=" + deptName + ", startTime=" + startTime + ", endTime=" + endTime);

        // 直接根据部门名称（文章来源）查找文章
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Article::getColumnId, Article::getArticleOrigin); // 只选择需要的字段
        if (StringUtils.isNotEmpty(deptName)) {
            // 只查询指定部门（分局）的文章
            wrapper.eq(Article::getArticleOrigin, deptName);
        }
        wrapper.ge(Article::getPubdate, startTime);
        wrapper.le(Article::getPubdate, endTime);
        wrapper.isNotNull(Article::getArticleOrigin);
        wrapper.ne(Article::getArticleOrigin, "");

        System.out.println("查询条件: " + wrapper.getSqlSegment());
        List<Article> articles = articleMapper.selectList(wrapper);
        System.out.println("查询结果数量: " + articles.size());

        if (articles.isEmpty()) {
            System.out.println("未查询到数据，返回空列表");
            return new ArrayList<>();
        }

        // 获取所有栏目信息
        List<Conlumn> allColumns = conlumnMapper.selectList(null);
        Map<Long, Conlumn> columnMap = new HashMap<>();
        for (Conlumn column : allColumns) {
            columnMap.put(column.getId(), column);
        }

        // 初始化所有栏目计数为0
        Map<String, Integer> columnCountMap = new HashMap<>();
        for (Conlumn column : allColumns) {
            columnCountMap.put(column.getName(), 0);
        }

        // 统计各栏目文章数量（不限制栏目权限）
        int classifiedCount = 0; // 用于统计已分类的文章数量
        for (Article article : articles) {
            Long columnId = article.getColumnId();
            if (columnId != null) {
                Conlumn column = columnMap.get(columnId);
                if (column != null) {
                    String columnName = column.getName();
                    columnCountMap.put(columnName, columnCountMap.getOrDefault(columnName, 0) + 1);
                    classifiedCount++; // 增加已分类文章计数
                }
            }
        }

        // 计算未知栏目的文章数量（总数量 - 已分类数量）
        int nullColumnCount = articles.size() - classifiedCount;
        if (nullColumnCount > 0) {
            columnCountMap.put("未知栏目", nullColumnCount);
        }

        // 转换为返回格式
        List<ArticleColumnVo> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : columnCountMap.entrySet()) {
            ArticleColumnVo vo = new ArticleColumnVo();
            vo.setColumnName(entry.getKey());
            vo.setCount(entry.getValue());
            result.add(vo);
        }

        // 按文章数量排序
        result.sort((a, b) -> b.getCount());

        System.out.println("最终结果: " + result);

        return result;
    }
    
    @Autowired
    private SysDeptMapper sysDeptMapper;
    
    @Override
    public List<ArticleColumnVo> selectArticleColumnListByDeptAndSubDepts(String deptName, String startTime, String endTime) {
        // 如果没有指定时间范围，默认查询本年1月1日到当前日期
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            String yearStart = DateUtils.dateTimeNow("yyyy") + "-01-01";
            String today = DateUtils.dateTimeNow("yyyy-MM-dd");
            startTime = yearStart;
            endTime = today;
        }

        System.out.println("输入参数: deptName=" + deptName + ", startTime=" + startTime + ", endTime=" + endTime);

        // 构建查询条件，查询指定部门及其子部门的文章
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Article::getColumnId, Article::getArticleOrigin); // 只选择需要的字段
        
        if (StringUtils.isNotEmpty(deptName)) {
            // 首先获取指定部门的ID
            SysDept dept = sysDeptMapper.selectDeptByName(deptName);
            if (dept != null) {
                // 获取该部门及其所有子部门的名称列表
                List<String> deptNames = new ArrayList<>();
                deptNames.add(deptName); // 添加自身
                
                // 递归获取所有子部门
                List<String> childDeptNames = getAllChildDeptNames(dept.getDeptId());
                deptNames.addAll(childDeptNames);
                
                System.out.println("部门及其子部门列表: " + deptNames);
                
                // 使用IN条件查询所有相关部门的文章
                wrapper.in(Article::getArticleOrigin, deptNames);
            } else {
                // 如果没找到部门，使用原来的LIKE查询
                wrapper.likeRight(Article::getArticleOrigin, deptName);
            }
        }
        
        wrapper.ge(Article::getPubdate, startTime);
        wrapper.le(Article::getPubdate, endTime);
        wrapper.isNotNull(Article::getArticleOrigin);
        wrapper.ne(Article::getArticleOrigin, "");

        System.out.println("查询条件: " + wrapper.getSqlSegment());
        List<Article> articles = articleMapper.selectList(wrapper);
        System.out.println("查询结果数量: " + articles.size());
        
        // 打印所有记录的部门来源用于调试
        if (!articles.isEmpty()) {
            System.out.println("所有记录的部门来源:");
            // 统计各个部门来源的数量
            Map<String, Integer> originCount = new HashMap<>();
            for (Article article : articles) {
                String origin = article.getArticleOrigin();
                originCount.put(origin, originCount.getOrDefault(origin, 0) + 1);
            }
            // 打印统计结果
            originCount.forEach((origin, count) -> 
                System.out.println("  - " + origin + ": " + count + " 条记录"));
        }

        if (articles.isEmpty()) {
            System.out.println("未查询到数据，返回空列表");
            return new ArrayList<>();
        }

        // 获取所有栏目信息
        List<Conlumn> allColumns = conlumnMapper.selectList(null);
        Map<Long, Conlumn> columnMap = new HashMap<>();
        for (Conlumn column : allColumns) {
            columnMap.put(column.getId(), column);
        }

        // 初始化所有栏目计数为0
        Map<String, Integer> columnCountMap = new HashMap<>();
        for (Conlumn column : allColumns) {
            columnCountMap.put(column.getName(), 0);
        }

        // 统计各栏目文章数量（不限制栏目权限）
        int classifiedCount = 0; // 用于统计已分类的文章数量
        for (Article article : articles) {
            Long columnId = article.getColumnId();
            if (columnId != null) {
                Conlumn column = columnMap.get(columnId);
                if (column != null) {
                    String columnName = column.getName();
                    columnCountMap.put(columnName, columnCountMap.getOrDefault(columnName, 0) + 1);
                    classifiedCount++; // 增加已分类文章计数
                }
            }
        }

        // 计算未知栏目的文章数量（总数量 - 已分类数量）
        int nullColumnCount = articles.size() - classifiedCount;
        if (nullColumnCount > 0) {
            columnCountMap.put("未知栏目", nullColumnCount);
        }

        // 转换为返回格式
        List<ArticleColumnVo> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : columnCountMap.entrySet()) {
            ArticleColumnVo vo = new ArticleColumnVo();
            vo.setColumnName(entry.getKey());
            vo.setCount(entry.getValue());
            result.add(vo);
        }

        // 按文章数量排序
        result.sort((a, b) -> b.getCount());

        System.out.println("最终结果数量: " + result.size());
        System.out.println("最终结果: " + result);

        return result;
    }
    
    /**
     * 递归获取所有子部门的名称
     * @param deptId 部门ID
     * @return 子部门名称列表
     */
    private List<String> getAllChildDeptNames(Long deptId) {
        List<String> childDeptNames = new ArrayList<>();
        
        // 获取直接子部门
        List<SysDept> childDepts = sysDeptMapper.selectChildrenDeptById(deptId);
        if (childDepts != null && !childDepts.isEmpty()) {
            for (SysDept childDept : childDepts) {
                childDeptNames.add(childDept.getDeptName());
                // 递归获取子部门的子部门
                childDeptNames.addAll(getAllChildDeptNames(childDept.getDeptId()));
            }
        }
        
        return childDeptNames;
    }

    @Override
    public List<ArticleColumnVo> selectArticleColumnList(String userName, String startTime, String endTime) {
        // 如果没有指定时间范围，默认查询本年1月1日到当前日期
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            String yearStart = DateUtils.dateTimeNow("yyyy") + "-01-01";
            String today = DateUtils.dateTimeNow("yyyy-MM-dd");
            startTime = yearStart;
            endTime = today;
        }

        System.out.println("输入参数: userName=" + userName + ", startTime=" + startTime + ", endTime=" + endTime);

        // 第一步：根据用户名查找文章，获取文章来源列表
        // 第一步查询：只查询来源字段，加快查询，sql优化
        LambdaQueryWrapper<Article> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.select(Article::getArticleOrigin); // 只选择需要的字段
        if (StringUtils.isNotEmpty(userName)) {
            userWrapper.eq(Article::getAuthor, userName);
        }
        userWrapper.ge(Article::getPubdate, startTime);
        userWrapper.le(Article::getPubdate, endTime);
        userWrapper.isNotNull(Article::getArticleOrigin);
        userWrapper.ne(Article::getArticleOrigin, "");

        System.out.println("第一步查询条件: " + userWrapper.getSqlSegment());
        List<Article> userArticles = articleMapper.selectList(userWrapper);
        System.out.println("第一步查询结果数量: " + userArticles.size());

        if (userArticles.isEmpty()) {
            System.out.println("第一步未查询到数据，返回空列表");
            return new ArrayList<>();
        }

        // 提取文章来源（过滤空值）
        Set<String> articleOrigins = new HashSet<>();
        for (Article article : userArticles) {
            if (StringUtils.isNotEmpty(article.getArticleOrigin())) {
                articleOrigins.add(article.getArticleOrigin());
            }
        }
        System.out.println("文章来源列表：" + articleOrigins);

        if (articleOrigins.isEmpty()) {
            System.out.println("没有有效的文章来源，返回空列表");
            return new ArrayList<>();
        }

        // 第二步：根据文章来源查找所有相关文章
        // 第二步查询：只查询统计需要的字段
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Article::getColumnId, Article::getArticleOrigin); // 只选择需要的字段
        wrapper.in(Article::getArticleOrigin, articleOrigins);
        wrapper.ge(Article::getPubdate, startTime);
        wrapper.le(Article::getPubdate, endTime);
        wrapper.isNotNull(Article::getArticleOrigin);
        wrapper.ne(Article::getArticleOrigin, "");

        List<Article> allArticles = articleMapper.selectList(wrapper);
        System.out.println("第二步查询结果数量: " + allArticles.size());

        // 第三步：进行过滤和统计
        // 先获取所有栏目信息
        List<Conlumn> allColumns = conlumnMapper.selectList(null);
        Map<Long, Conlumn> columnMap = new HashMap<>();
        for (Conlumn column : allColumns) {
            columnMap.put(column.getId(), column);
        }

        // 统计各栏目文章数量（不限制栏目权限）
        Map<String, Integer> columnCountMap = new HashMap<>();
        for (Article article : allArticles) {
            Long columnId = article.getColumnId();
            if (columnId != null) {
                Conlumn column = columnMap.get(columnId);
                if (column != null) {
                    String columnName = column.getName();
                    columnCountMap.put(columnName, columnCountMap.getOrDefault(columnName, 0) + 1);
                }
            }
        }

        // 转换为返回格式
        List<ArticleColumnVo> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : columnCountMap.entrySet()) {
            ArticleColumnVo vo = new ArticleColumnVo();
            vo.setColumnName(entry.getKey());
            vo.setCount(entry.getValue());
            result.add(vo);
        }

        // 按文章数量排序
        result.sort((a, b) -> b.getCount());

        System.out.println("最终结果: " + result);

        return result;
    }





    // 计算日期区间的文章来源及对应的新闻数量
    @Override
    public List<ArticleOriginDateVo> selectArticleOriginDateList(String startTime, String endTime) {
        // 如果没有指定时间范围，默认查询本年1月1日到当前日期
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            String yearStart = DateUtils.dateTimeNow("yyyy") + "-01-01";
            String today = DateUtils.dateTimeNow("yyyy-MM-dd");
            startTime = yearStart;
            endTime = today;
        }

        // 构建查询条件
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(StringUtils.isNotEmpty(startTime), Article::getPubdate, startTime);
        wrapper.le(StringUtils.isNotEmpty(endTime), Article::getPubdate, endTime);
        wrapper.isNotNull(Article::getArticleOrigin);
        wrapper.ne(Article::getArticleOrigin, "");

        return articleMapper.selectArticleOriginDateList(wrapper);
    }

    // 按部门统计文章数量
    @Override
    public List<DeptArticleCountVo> selectDeptArticleCountList(String startTime, String endTime) {
        // 如果没有指定时间范围，默认查询本年1月1日到当前日期
        if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
            String yearStart = DateUtils.dateTimeNow("yyyy") + "-01-01";
            String today = DateUtils.dateTimeNow("yyyy-MM-dd");
            startTime = yearStart;
            endTime = today;
        }

        // 获取荆州市长江河道管理局的下一级部门列表（市局/总局和各分局）
        List<SysDept> firstLevelDepts = getFirstLevelDepts();
        System.out.println("部门列表："+firstLevelDepts);

        List<DeptArticleCountVo> result = new ArrayList<>();

        // 对每个部门统计文章数量
        for (SysDept dept : firstLevelDepts) {
            // 获取该部门及其所有子部门的名称列表
            List<String> deptNames = new ArrayList<>();
            deptNames.add(dept.getDeptName()); // 添加自身
            List<String> childDeptNames = getAllChildDeptNames(dept.getDeptId());
            deptNames.addAll(childDeptNames);

            // 构建查询条件
            LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
            wrapper.ge(StringUtils.isNotEmpty(startTime), Article::getPubdate, startTime);
            wrapper.le(StringUtils.isNotEmpty(endTime), Article::getPubdate, endTime);
            wrapper.in(Article::getArticleOrigin, deptNames);

            // 统计文章数量
            int count = Math.toIntExact(articleMapper.selectCount(wrapper));

            // 创建结果对象
            DeptArticleCountVo vo = new DeptArticleCountVo();
            vo.setDeptName(dept.getDeptName());
            vo.setCount(count);
            result.add(vo);
        }

        // 按文章数量排序
        result.sort((a, b) -> b.getCount() - a.getCount());

        return result;
    }

    /**
     * 获取荆州市长江河道管理局的下一级部门列表
     * @return 下一级部门列表
     */
    private List<SysDept> getFirstLevelDepts() {
        List<SysDept> result = new ArrayList<>();

        // 获取荆州市长江河道管理局
        SysDept jingzhouDept = sysDeptMapper.selectDeptByName("荆州市长江河道管理局");
        if (jingzhouDept != null) {
            // 获取其直接子部门
            List<SysDept> childDepts = sysDeptMapper.selectChildrenDeptById(jingzhouDept.getDeptId());
            if (childDepts != null) {
                for (SysDept childDept : childDepts) {
                    // 添加市局/总局和其他分局
                    if ("市局/总局".equals(childDept.getDeptName()) || isDirectSubDeptOfJingZhou(childDept)) {
                        result.add(childDept);
                    }
                }
            }
        }

        return result;
    }



    @Override
    public List<RecoverStation> updateArticleDeletedStatus(Long[] articleIds) {
        //删除数据到回收站
        List<RecoverStation> recoverStations = new ArrayList<>();
        for (Long articleId : articleIds){
            Article article = this.getById(articleId);
            //回收站数据
            RecoverStation recoverStation = new RecoverStation();
            if (article != null){
                recoverStation.setArticleId(articleId);
                if (article.getTitle()!= null)
                    recoverStation.setTitle(article.getTitle());
                if (article.getArticleOrigin()!= null)
                    recoverStation.setArticleOrigin(article.getArticleOrigin());
                if (article.getColumnId()!= null)
                    recoverStation.setColumnId(article.getColumnId());
                if (article.getContent()!= null)
                    recoverStation.setContent(article.getContent());
                if (article.getAuthor()!= null)
                    recoverStation.setAuthor(article.getAuthor());
                if (article.getCreateBy()!= null)
                    recoverStation.setCreateBy(article.getCreateBy());
                if (article.getUpdateBy()!= null)
                    recoverStation.setUpdateBy(article.getUpdateBy());
                if (article.getUpdateTime()!= null)
                    recoverStation.setUpdateTime(article.getUpdateTime());
                if (article.getCreateTime()!= null)
                    recoverStation.setCreateTime(article.getCreateTime());
                if (article.getRemark()!= null)
                    recoverStation.setRemark(article.getRemark());
                if (article.getCoverPath()!= null)
                    recoverStation.setCoverPath(article.getCoverPath());
                if (article.getIp()!= null)
                    recoverStation.setIp(article.getIp());
                if (article.getPubdate()!= null)
                    recoverStation.setPubdate(article.getPubdate());
                if (article.getAppval()!= null)
                    recoverStation.setAppval(article.getAppval());
                if (article.getAuditId()!= null)
                    recoverStation.setAuditId(article.getAuditId());
                if (article.getLittleTitle1()!= null)
                    recoverStation.setLittleTitle1(article.getLittleTitle1());
                if (article.getLittleTitle2()!= null)
                    recoverStation.setLittleTitle2(article.getLittleTitle2());
                if (article.getStatus()!= null)
                    recoverStation.setStatus(article.getStatus());
                //附件路径
                if (article.getAttachment()!= null)
                    recoverStation.setAttachment(article.getAttachment());
                //pdf图片路径
                if (article.getPdfImagePaths()!= null)
                    recoverStation.setPdfImagePaths(article.getPdfImagePaths());
                // 设置默认有效期为30天
                recoverStation.setValidDate(30);
                recoverStation.setType(0L);//类型为已审核的文章数据回收
            }
            recoverStations.add(recoverStation);
            recoverStationMapper.insertRecoverStation(recoverStation);
        }
        return recoverStations;
    }

    @Override
    public List<Article> selectArticleListByRole(boolean isAdmin, Article article) {
        return articleMapper.selectArticleListByRole(isAdmin,article);
    }

    /**
     * 查询article
     *
     * @param articleId article主键
     * @return article
     */
    @Override
    public Article selectArticleByArticleId(Long articleId) {
        return articleMapper.selectArticleByArticleId(articleId);
    }

    /**
     * 查询article列表
     *
     * @param article article
     * @return article
     */
    @Override
    public List<Article> selectArticleList(Article article) {
        return articleMapper.selectArticleList(article);
    }

    /**
     * 新增article
     *
     * @param article article
     * @return 结果
     */
    @Override
    public int insertArticle(Article article, String articleName) {
        article.setCreateTime(DateUtils.getNowDate());

        LambdaQueryWrapper<Conlumn> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Conlumn::getName,articleName);
        Conlumn conlumn = conlumnMapper.selectOne(lambdaQueryWrapper);
        if(null!=conlumn|| StringUtils.isNull(conlumn)){
            article.setColumnId(conlumn.getId());
        }

        // 检查是否需要清除PDF图片预览路径
        if (article.getAttachment() == null || article.getAttachment().isEmpty()) {
            article.setPdfImagePaths(null);
        }

        // 先插入文章
        int result = articleMapper.insertArticle(article);

        // 如果文章有PDF附件，异步解析PDF为图片
        if (result > 0 && article.getAttachment() != null && !article.getAttachment().isEmpty()) {
            // 检查附件是否为PDF文件
            if (article.getAttachment().toLowerCase().endsWith(".pdf")) {
                // 异步处理PDF解析任务
                pdfParseTaskService.processPdfParseTask(article.getArticleId());
            }
        }

        return result;
    }

    /**
     * 修改article
     *
     * @param article article
     * @return 结果
     */
    @Override
    public int updateArticle(Article article, String articleName) {
        LambdaQueryWrapper<Conlumn> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Conlumn::getName,articleName);
        Conlumn conlumn = conlumnMapper.selectOne(lambdaQueryWrapper);
        if(null!=conlumn|| StringUtils.isNull(conlumn)){
            article.setColumnId(conlumn.getId());
        }

        // 检查是否需要清除PDF图片预览路径
        if (article.getAttachment() == null || article.getAttachment().isEmpty()) {
            article.setPdfImagePaths(null);
        }

        // 更新文章
        int result = articleMapper.updateArticle(article);

        // 如果文章有PDF附件，异步解析PDF为图片
        if (result > 0 && article.getAttachment() != null && !article.getAttachment().isEmpty()) {
            // 检查附件是否为PDF文件
            if (article.getAttachment().toLowerCase().endsWith(".pdf")) {
                // 异步处理PDF解析任务
                pdfParseTaskService.processPdfParseTask(article.getArticleId());
            }
        }

        return result;
    }

    /**
     * 批量删除article
     *
     * @param articleIds 需要删除的article主键
     * @return 结果
     */
    @Override
    public int deleteArticleByArticleIds(Long[] articleIds) {
        return articleMapper.deleteArticleByArticleIds(articleIds);
    }

    /**
     * 删除article信息
     *
     * @param articleId article主键
     * @return 结果
     */
    @Override
    public int deleteArticleByArticleId(Long articleId) {
        return articleMapper.deleteArticleByArticleId(articleId);
    }

    /**
     * 根据auditId删除article
     *
     * @param auditId auditId
     * @return 结果
     */
    @Override
    public int deleteArticleByAuditId(Long auditId) {
            return articleMapper.deleteArticleByAuditId(auditId);
    }

    /**
     * 隐藏文章
     *
     * @param articleId 文章主键
     * @return 结果
     */
    @Override
    public int hideArticle(Long articleId) {
        return articleMapper.hideArticle(articleId);
    }

    /**
     * 显示文章
     *
     * @param articleId 文章主键
     * @return 结果
     */
    @Override
    public int showArticle(Long articleId) {
        return articleMapper.showArticle(articleId);
    }

    /**
     * 批量隐藏文章
     *
     * @param articleIds 文章主键数组
     * @return 结果
     */
    @Override
    public int batchHideArticle(Long[] articleIds) {
        return articleMapper.batchHideArticle(articleIds);
    }

    /**
     * 批量显示文章
     *
     * @param articleIds 文章主键数组
     * @return 结果
     */
    @Override
    public int batchShowArticle(Long[] articleIds) {
        return articleMapper.batchShowArticle(articleIds);
    }
}
